package com.example.myprojectoffeixue;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ExpandableListView;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import org.apache.http.entity.StringEntity;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

//本fg是场景fragment，3个gridview，对应三中类型的场景，主要的逻辑是
// 1、根据顺序依次获取场景数据
//2、5秒之后默认为获取场景失败
public class ChangJingfg extends Fragment {
    public GridView gd;
    public GridView gd1;
    public GridView gd2;
    Dialog dialog;
    private List<Websocketutil> u;
    private MyApplication m;
    private ArrayList<SheBeiClass> sb2;
    public int flag1 = 1;
    int i;
    private TextView tv1;
    private TextView tv2;
    private TextView tv3;
    private ArrayList<CJutil> cj;
    Cjadapter c1;
    Cjadapter c2;
    Cjadapter c3;
    @Override
    public void onStart() {
        Log.d("场景","cj");
        if(!MyApplication.localflag){
        Getscen();}
        super.onStart();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View r = inflater.inflate(R.layout.activity_my_cj, container, false);
        gd = (GridView) r.findViewById(R.id.gd_mcj);
        gd1 = (GridView) r.findViewById(R.id.gd1_mcj);
        gd2 = (GridView) r.findViewById(R.id.gd2_mcj);
        tv2 = (TextView) r.findViewById(R.id.tv1_changjing);
        tv1 = (TextView) r.findViewById(R.id.tv_changjing);
        tv3 = (TextView) r.findViewById(R.id.tv2_changjing);
        ImageView iv2 = (ImageView) r.findViewById(R.id.iv_kaiguanfg1);
        m = (MyApplication) getActivity().getApplication();
        iv2.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if(!MyApplication.localflag){
                Intent it = new Intent(getActivity(), AddCJActivity.class);
                it.putExtra("clear","clear");
                startActivity(it);}else{
                    ToastUtils.showToast(getActivity(),"当前环境不支持添加场景");

                }
            }
        });

        gd.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view, final int position, long id) {
                Startscen(m.s_cj.get(position).sceneId, 1, position);
            }
        });

        gd1.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view, final int position, long id) {

                if ("1".equals(m.time_cj.get(position).sceneStatus)) {
                    Startscen(m.time_cj.get(position).sceneId, 2, position);
                } else  if("2".equals(m.time_cj.get(position).sceneStatus)){
                    Stopscen(position, m.time_cj.get(position).sceneId, 2);
                }


            }

        });
        gd2.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view, final int position, long id) {

                if ("1".equals(m.l_cj.get(position).sceneStatus)) {

                    Startscen(m.l_cj.get(position).sceneId, 3, position);
                } else if ("2".equals(m.l_cj.get(position).sceneStatus)) {
                    Stopscen(position, m.l_cj.get(position).sceneId, 3);

                }


            }

        });


        gd.setOnItemLongClickListener(new OnItemLongClickListener() {

            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, final int position, long id) {

                dialog = new Dialog(getActivity(),R.style.dialog);
                dialog.setContentView(R.layout.yaokongqidialog);
                TextView tv = (TextView) dialog.findViewById(R.id.restudy);
                TextView delete = (TextView) dialog.findViewById(R.id.delete);
                TextView iv1 = (TextView) dialog.findViewById(R.id.iv1_mydialog);
                iv1.setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        dialog.dismiss();
                    }
                });
                tv.setText("修改场景");
                dialog.show();
                tv.setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        getSceneDetail(position,m.s_cj.get(position).sceneId);

                    }
                });


                delete.setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        dialog.dismiss();
                        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());

                        builder.setMessage("确认删除吗?");

                        builder.setTitle("提示");

                        builder.setPositiveButton("确认", new Dialog.OnClickListener() {

                            @Override

                            public void onClick(DialogInterface dialog, int which) {

                                deleteScene(position,m.s_cj.get(position).sceneId,1);
                            }
                        });
                        builder.setNegativeButton("取消", new Dialog.OnClickListener() {

                            @Override

                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                            }
                        });
                        builder.create().show();
                    }
                });

                return true;
            }
        });


        gd1.setOnItemLongClickListener(new OnItemLongClickListener() {

            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, final int position, long id) {


                 dialog = new Dialog(getActivity(),R.style.dialog);
                dialog.setContentView(R.layout.yaokongqidialog);
                TextView tv = (TextView) dialog.findViewById(R.id.restudy);
                TextView delete = (TextView) dialog.findViewById(R.id.delete);
                TextView iv1 = (TextView) dialog.findViewById(R.id.iv1_mydialog);
                iv1.setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        dialog.dismiss();

                    }
                });
                tv.setText("修改场景");
                dialog.show();
                tv.setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if("1".equals(m.time_cj.get(position).sceneStatus)){
                            getSceneDetail(position,m.time_cj.get(position).sceneId);}else{
                            HttpConnection.showToast(getActivity(),"请先关闭场景");

                        }
                    }
                });


                delete.setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        dialog.dismiss();
                        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());

                        builder.setMessage("确认删除吗?");

                        builder.setTitle("提示");

                        builder.setPositiveButton("确认", new Dialog.OnClickListener() {

                            @Override

                            public void onClick(DialogInterface dialog, int which) {

                                deleteScene(position,m.time_cj.get(position).sceneId,2);
                            }
                        });
                        builder.setNegativeButton("取消", new Dialog.OnClickListener() {

                            @Override

                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                            }
                        });
                        builder.create().show();
                    }
                });

                return true;
            }
        });


        gd2.setOnItemLongClickListener(new OnItemLongClickListener() {

            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, final int position, long id) {

                 dialog = new Dialog(getActivity(),R.style.dialog);
                dialog.setContentView(R.layout.yaokongqidialog);
                TextView tv = (TextView) dialog.findViewById(R.id.restudy);
                TextView delete = (TextView) dialog.findViewById(R.id.delete);
                TextView iv1 = (TextView) dialog.findViewById(R.id.iv1_mydialog);
                iv1.setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        dialog.dismiss();
                    }
                });
                tv.setText("修改场景");
                dialog.show();
                tv.setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if("1".equals(m.l_cj.get(position).sceneStatus)){
                            getSceneDetail(position,m.l_cj.get(position).sceneId);}else{
                            HttpConnection.showToast(getActivity(),"请先关闭场景");
                        }




                    }
                });


                delete.setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        dialog.dismiss();
                        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());

                        builder.setMessage("确认删除吗?");

                        builder.setTitle("提示");

                        builder.setPositiveButton("确认", new Dialog.OnClickListener() {

                            @Override

                            public void onClick(DialogInterface dialog, int which) {
                                deleteScene(position,m.l_cj.get(position).sceneId,3);
                            }
                        });
                        builder.setNegativeButton("取消", new Dialog.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                            }
                        });
                        builder.create().show();
                    }
                });

                return true;
            }
        });
        return r;
    }


    public void Getscen() {
        c1=null;
        c2=null;
        c3=null;
        m = (MyApplication) getActivity().getApplication();
        m.s_cj.clear();
        m.l_cj.clear();
        m.time_cj.clear();
        GateWay Gw = new GateWay();
        Gw.userId = m.userId;
        String j = JSON.toJSONString(Gw);
        j = AESUtil.encrypt(j);
        HttpUtils httpUtils = new HttpUtils();
        RequestParams params = new RequestParams();
        params.setHeader("Content-Type", "application/json");
        try {
            params.setBodyEntity(new StringEntity(j, "utf-8"));
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        httpUtils.send(HttpRequest.HttpMethod.POST, HttpConnection.getSceneList, params,
                new RequestCallBack<String>() {

                    @Override
                    public void onFailure(HttpException arg0, String arg1) {
                        ToastUtils.showToast(getActivity(),"网络异常");
                    }

                    @Override
                    public void onSuccess(ResponseInfo<String> arg0) {
                        if (arg0.result != null && !("".equals(arg0.result))) {
                            arg0.result = AESUtil.decrypt(arg0.result);
                            JSONObject jb = JSONObject.parseObject(arg0.result);
                            JSONArray ja = jb.getJSONArray("sceneList");
                            String msg = jb.getString("msg");
                            if ("成功".equals(msg)) {
                                cj = (ArrayList<CJutil>) JSON.parseArray(ja.toString(), CJutil.class);
                                for (int i = 0; i < cj.size(); i++) {

                                    if (cj.get(i).sceneType == 1) {
                                       m.s_cj.add(cj.get(i));
                                    } else if (cj.get(i).sceneType == 2) {
                                       m.time_cj.add(cj.get(i));
                                    } else if (cj.get(i).sceneType == 3) {

                                       m.l_cj.add(cj.get(i));
                                    }
                                }
                               if (m.s_cj.size() != 0) {
                                    tv1.setVisibility(View.VISIBLE);
                                }

                                if (m.time_cj.size() != 0) {
                                    tv2.setVisibility(View.VISIBLE);
                                }
                                if (m.l_cj.size() != 0) {
                                    tv3.setVisibility(View.VISIBLE);
                                }
                                c1 = new Cjadapter(getActivity(), m.s_cj, 1);
                                c2 = new Cjadapter(getActivity(), m.time_cj, 2);
                                c3 = new Cjadapter(getActivity(), m.l_cj, 3);
                                gd.setAdapter(c1);
                                gd1.setAdapter(c2);
                                gd2.setAdapter(c3);
                            }else{
                                HttpConnection.toastLog("服务器错误", getActivity());
                            }
                        } else {
                            ToastUtils.showToast(getActivity(),"服务器错误");
                        }
                    }
                });
    }
    public void Startscen(int sceneId, final int ScenType, final int postion) {
        CJutil cj2 = new CJutil();
        cj2.sceneId = sceneId;
        cj2.sceneType = ScenType;
        String j = JSON.toJSONString(cj2);
        j = AESUtil.encrypt(j);
        HttpUtils httpUtils = new HttpUtils();
        RequestParams params = new RequestParams();
        params.setHeader("Content-Type", "application/json");
        try {
            params.setBodyEntity(new StringEntity(j, "utf-8"));
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        httpUtils.send(HttpRequest.HttpMethod.POST, HttpConnection.startupScene, params,
                new RequestCallBack<String>() {

                    @Override
                    public void onFailure(HttpException arg0, String arg1) {
                        ToastUtils.showToast(getActivity(),"网络异常");
                    }

                    @Override
                    public void onSuccess(ResponseInfo<String> arg0) {
                        if (arg0.result != null && !("".equals(arg0.result))) {
                            arg0.result = AESUtil.decrypt(arg0.result);
                            JSONObject jb = JSONObject.parseObject(arg0.result);
                            JSONArray ja = jb.getJSONArray("sceneList");
                            String msg = jb.getString("msg");
                            if ("成功".equals(msg)) {

                                HttpConnection.toastLog("场景启用成功", getActivity());

                                if (ScenType == 2) {
                                    m.time_cj.get(postion).sceneStatus = "2";
                                    c2.notifyDataSetChanged();
                                } else if (ScenType == 3) {
                                    m.l_cj.get(postion).sceneStatus = "2";
                                    c3.notifyDataSetChanged();
                                }
                            }else{
                                HttpConnection.toastLog("服务器错误", getActivity());
                            }
                        } else {
                            HttpConnection.toastLog("服务器错误", getActivity());
                        }
                    }

                });

    }

    public void Stopscen(final int postion, int ScenId, final int ScenType) {

        final CJutil cj2 = new CJutil();
        cj2.sceneId = ScenId;
        cj2.sceneType = ScenType;
        String j = JSON.toJSONString(cj2);
        j = AESUtil.encrypt(j);
        HttpUtils httpUtils = new HttpUtils();
        RequestParams params = new RequestParams();
        params.setHeader("Content-Type", "application/json");
        try {
            params.setBodyEntity(new StringEntity(j, "utf-8"));
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        httpUtils.send(HttpRequest.HttpMethod.POST, HttpConnection.shutdownScene, params,
                new RequestCallBack<String>() {

                    @Override
                    public void onFailure(HttpException arg0, String arg1) {
                        HttpConnection.toastLog("网络异常", getActivity());
                    }
                    @Override
                    public void onSuccess(ResponseInfo<String> arg0) {
                        if (arg0.result != null && !("".equals(arg0.result))) {
                            arg0.result = AESUtil.decrypt(arg0.result);
                            JSONObject jb = JSONObject.parseObject(arg0.result);
                            String msg = jb.getString("msg");
                            if ("成功".equals(msg)) {
                                 HttpConnection.toastLog("场景关闭", getActivity());
                                if (ScenType == 2) {
                                    m.time_cj.get(postion).sceneStatus = "1";
                                    c2.notifyDataSetChanged();
                                } else if (ScenType == 3) {
                                    m.l_cj.get(postion).sceneStatus = "1";
                                    c3.notifyDataSetChanged();
                                }
                            }else{
                                HttpConnection.toastLog("服务器错误", getActivity());
                            }
                        } else {
                            HttpConnection.toastLog("服务器错误", getActivity());
                        }
                    }

                });
    }
    public void deleteScene(final int postion, int ScenId, final int ScenType) {

        final CJutil cj2 = new CJutil();
        cj2.sceneId = ScenId;
        String j = JSON.toJSONString(cj2);
        j = AESUtil.encrypt(j);
        HttpUtils httpUtils = new HttpUtils();
        RequestParams params = new RequestParams();
        params.setHeader("Content-Type", "application/json");
        try {
            params.setBodyEntity(new StringEntity(j, "utf-8"));
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        httpUtils.send(HttpRequest.HttpMethod.POST, HttpConnection.deleteScene, params,
                new RequestCallBack<String>() {

                    @Override
                    public void onFailure(HttpException arg0, String arg1) {
                        HttpConnection.toastLog("网络异常", getActivity());
                    }

                    @Override
                    public void onSuccess(ResponseInfo<String> arg0) {
                        if (arg0.result != null && !("".equals(arg0.result))) {
                            arg0.result = AESUtil.decrypt(arg0.result);
                            JSONObject jb = JSONObject.parseObject(arg0.result);
                            String msg = jb.getString("msg");
                            if ("成功".equals(msg)) {
                                if (ScenType == 2) {
                                    m.time_cj.remove(postion);
                                    if(m.time_cj.size()==0){
                                        tv2.setVisibility(View.GONE);
                                    }
                                    c2.notifyDataSetChanged();
                                } else if (ScenType == 3) {
                                    m.l_cj.remove(postion);
                                    if(m.l_cj.size()==0){
                                        tv3.setVisibility(View.GONE);
                                    }
                                    c3.notifyDataSetChanged();
                                }else if(ScenType==1){
                                    m.s_cj.remove(postion);
                                    if(m.s_cj.size()==0){
                                        tv1.setVisibility(View.GONE);
                                    }
                                    c1.notifyDataSetChanged();

                                }
                            }else{
                                HttpConnection.toastLog("服务器错误", getActivity());
                            }
                        } else {
                            HttpConnection.toastLog("服务器错误", getActivity());

                        }
                    }

                });


    }




    public void getSceneDetail(final int postion, final int ScenId) {

        final CJutil cj2 = new CJutil();
        cj2.sceneId = ScenId;
        String j = JSON.toJSONString(cj2);
        j = AESUtil.encrypt(j);
        HttpUtils httpUtils = new HttpUtils();
        RequestParams params = new RequestParams();
        params.setHeader("Content-Type", "application/json");
        try {
            params.setBodyEntity(new StringEntity(j, "utf-8"));
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        httpUtils.send(HttpRequest.HttpMethod.POST, HttpConnection.getSceneDetail, params,
                new RequestCallBack<String>() {

                    @Override
                    public void onFailure(HttpException arg0, String arg1) {
                        HttpConnection.toastLog("网络异常", getActivity());
                    }

                    @Override
                    public void onSuccess(ResponseInfo<String> arg0) {
                        if (arg0.result != null && !("".equals(arg0.result))) {
                            arg0.result = AESUtil.decrypt(arg0.result);
                            JSONObject jb = JSONObject.parseObject(arg0.result);
                            String msg = jb.getString("msg");
                            if ("成功".equals(msg)) {
                               JSONObject obj=jb.getJSONObject("sceneDetail");
                                m.cj= JSON.parseObject(obj.toString(),CJutil.class);
                                if(m.cj.sceneType==3){
                                    if("010D".equals(m.cj.deviceId)) {
                                        m.cj.sceneType=4;
                                    }else{
                                        m.cj.sceneType=3;
                                    }

                                }
                                Intent it = new Intent(getActivity(), AddCJActivity.class);
                                m.ScenId=ScenId;
                                it.putExtra("kinds_flag", m.cj.sceneType);
                                dialog.dismiss();
                                startActivity(it);
                            }else{
                                HttpConnection.toastLog("服务器错误", getActivity());
                            }
                        } else {
                            HttpConnection.toastLog("服务器错误", getActivity());

                        }
                    }
                });
    }
}

